<?php

namespace App\Models;

use App\Engine\BaseModel;
use Illuminate\Database\Eloquent\Model;
use App\Engine\TokenService;

class User extends BaseModel
{
    protected $fillable=['openid','headpic','nickname','login_time','login_ip','mobile','money','invite_id'];
    
    public function getNicknameAttribute($value)
    {
        if($value=='')
            return $value;
        return base64_decode($value);
    }

    public function setNicknameAttribute($value)
    {
        $this->attributes['nickname']=base64_encode($value);
    }

    public function getLoginTimeAttribute($value)
    {
        if($value=='')
            return $value;
        return date('Y-m-d H:i:s',$value);
    }
    
     //获取小程序token
    public static function get_xcx_token($data)
    {
        $user=self::where('openid',$data['openid'])->first();
        if(!$user){
            $user=self::create($data);
        }
        $user->session_key=$data['session_key'];
        $user->save();
        $cache=[
            'uid'=>$user['id']
        ];
        $token=(new TokenService())->saveCache($cache);
        return ['token'=>$token];
    }
}
